package com.iwithlong.service.impl;

import com.imesne.assistant.jdbc.command.entity.Select;
import com.imesne.assistant.jdbc.persist.JdbcDao;
import com.iwithlong.entity.OperateLog;
import com.iwithlong.service.OperateLogService;
import com.iwithlong.vo.OperateLogVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * User : liulu
 * Date : 17-9-9 下午5:58
 * version $Id: OperateLogService.java, v 0.1 Exp $
 */
@Service
public class OperateLogServiceImpl implements OperateLogService {

    @Resource
    private JdbcDao jdbcDao;

    @Override
    public List<OperateLog> pageList(OperateLogVo logVo) {

        Select<OperateLog> select = jdbcDao.createSelect(OperateLog.class).where("1", 1);

        if (StringUtils.isNoneEmpty(logVo.getOperator())) {
            select.and("operator", logVo.getOperator());
        }

        if (StringUtils.isNoneEmpty(logVo.getOperatorType())) {
            select.and("operatorType", logVo.getOperatorType());
        }

        if (logVo.getStartTime() != null) {

            Calendar start = Calendar.getInstance();
            start.setTime(logVo.getStartTime());
            start.set(Calendar.HOUR_OF_DAY, 0);
            start.set(Calendar.MINUTE, 0);
            start.set(Calendar.SECOND, 0);

            select.and("logTime", ">=", new Object[]{start.getTime()});
        }

        if (logVo.getEndTime() != null) {
            Calendar end = Calendar.getInstance();
            end.setTime(logVo.getEndTime());
            end.set(Calendar.HOUR_OF_DAY, 23);
            end.set(Calendar.MINUTE, 59);
            end.set(Calendar.SECOND, 59);

            select.and("logTime", "<=", new Object[]{end.getTime()});
        }

        select.orderBy("logTime").desc();

        return select.pageList(logVo);
    }

    @Override
    public OperateLog get(Long operateLogId) {

        if (operateLogId == null) {
            return new OperateLog();
        }
        return jdbcDao.get(OperateLog.class, operateLogId);
    }

    @Override
    public void log(OperateLog log) {
        log.setLogTime(new Date());
        jdbcDao.insert(log);
    }
}
